<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Repositories\MemberRepositoryEloquent;
use App\User;
//use App\Models\UserRelationship;
use Breadcrumbs, Hash,Auth,Toastr,Config,Validator,DB,Carbon;
use Illuminate\Http\Request;
use App\Http\Requests\Home\User\UpdatePasswordRequest;
use App\Models\FinancialDetails;

use EasyWeChat\Payment\Order;
use Image;

class MemberController extends Controller{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;


    }

    public function userinfo(Request $request){
        $user = $request->user();
        //dd($user);
        $userparentid=base64_encode($user->id);
        // $share_url = url('/register/base64_encode($user->id)',['userparentid'=>base64_encode($user->id)]);
        $share_url = url('/register/'.$userparentid);
        //dd($share_url);
        return view('home.user.index',compact('user','share_url'));

    }

    public function password(Request $request){
        $user = Auth::user();
        $hashedPassword=$user->getAuthPassword();
        //if (Hash::check('8888881', $hashedPassword)) {
            //echo '密码相同';
        //}
        //echo $hashedPassword;
        return view('home.user.password',compact('user'));
    }

    public function passwordUpdate(Request $request){
        $user = Auth::user();
        $validator = Validator::make($request->all(), [
            'oldpwd' => 'required|min:6',
            'password' => 'required|min:6|confirmed',
        ]);

        $validator->after(function($validator) use($user,$request) {
            
            $hashedPassword=$user->getAuthPassword();
            if (!Hash::check($request->oldpwd, $hashedPassword)) {
                $validator->errors()->add('oldpwd', '原密码错误!');
            }
            
        });

        if ($validator->fails()) {
            //dd($validator->errors());
            return redirect()
                        ->back()
                        ->withErrors($validator)
                        ->withInput();
        }

        $user->fill([
            'password' => bcrypt($request->password)
        ])->save();

        return redirect('/password')->with('msg','修改成功');
                       
        //return view('home.user.password',compact('user'));
    }

    /**
     * [financialDetails 收支明细]
     * @return [type] [description]
     */
    public function financialDetails(){
        $user = Auth::user();
        $details = FinancialDetails::where('user_id','=',$user->id)->orderBy('id','desc')->simplePaginate(5);
        return view('home.user.income',compact('details'));
    }
    
    public function recharge(Request $request){
        $user = $request->user();
        //dd($user);
        return view('home.payment.recharge',compact('user'));
    }

    public function weiXinPay(Request $request){
        
        $this->validate($request, [
            'money' => 'required|numeric|min:0.01'
        ]);


        $user = $request->user();

        $userwxinfo = session('wechat.oauth_user'); // 拿到授权用户资料
        //dd($userwxinfo);
        $wechat = app('wechat');
        $payment = $wechat->payment;

        $data = array();
        $money = $request->money;
        $data['user_id'] = $user->id;
        $data['money'] = $money;
        $data['fee'] = $money*0.006;
        $data['status'] = 0;
        $data['type'] = 1;
        $data['created_at'] = \Carbon\Carbon::now()->toDateTimeString();
        //$data['bank_id'] = 0;
        //商户单号
        $out_trade_no = $user->id.date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        //$res = M('FuturesRecharge')->add($data);
        $id = DB::table('recharges')->insertGetId($data);
        if(!$id){
            echo 'Error';exit;
        }
        $notify_url = url('wxpaynotify');
        //echo $notify_url;
        //dd($payment);
        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'openid'           => $user->openid,
            'body'             => '平台充值',
            'detail'           => '账户充值'.$money.'元',
            'out_trade_no'     => $out_trade_no,
            'total_fee'        => $money*100,
            'notify_url'       => $notify_url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            // ...
        ];
        $order = new Order($attributes);
        //var_dump($order);
        $result = $payment->prepare($order);
        //var_dump($order->total_fee);
        //var_dump($result);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId);
            //echo $prepayId;
            return view('home.payment.comfirmrecharge',compact('result','order','config'));
        }else{
            echo $result->return_msg;
        }


    }

    public function wxPayNotify(Request $request){
        //$file = './wxtest1.txt';
        //file_put_contents($file, $request["out_trade_no"].'-2');
        $app = app('wechat');
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $out_trade_no = $notify->out_trade_no;   //查询订单
            $recharge = DB::table('recharges')
                ->where('out_trade_no', '=', $out_trade_no)
                ->where('status','=',0)->first();

            if (!$recharge) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态
            if ($recharge->status==1) { // 假设订单字段“支付时间”不为空代表已经支付
                return true; // 已经支付成功了就不再更新了
            }
            // 用户是否支付成功
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $set = array();
                $set['transaction_id'] = $notify->transaction_id;
                $set['status'] = 1;
                $set['pay_time'] = date('Ymd H:i:s');
               
                $res = DB::table('recharges')->where('id','=',$recharge->id)->update($set);
                if(!$res){
                    return false;
                }
                $user = $this->user->find($recharge->user_id);
                if($user){
                    //file_put_contents($file,$user->mobile.'-13456');
                    $this->user->modifyBalance($user->id,$recharge->money,1,'账户充值');
                }

            } else { // 用户支付失败
                $recharge->status = 'paid_fail';
            }
            $recharge->save(); // 保存订单
            return true; // 返回处理完成
        });
        return $response;
    }



    public function saoMaPay(Request $request){

        $this->validate($request, [
            'money' => 'required|numeric|min:10'
        ]);

        $user = $request->user();
        
        include ('phpqrcode.php');
        require_once('merchant.php');

        $data = array();
        $money = $request->money;
        $data['user_id'] = $user->id;
        $data['money'] = $money;
        $data['fee'] = $money*0.009;
        $data['status'] = 0;
        $data['type'] = 2;
        $data['created_at'] = \Carbon\Carbon::now()->toDateTimeString();
        //$data['bank_id'] = 0;
        //商户单号
        $merchant_code = "2020600810";
        $out_trade_no = $user->id.date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        //$res = M('FuturesRecharge')->add($data);
        $id = DB::table('recharges')->insertGetId($data);
        if(!$id){
            echo 'Error';exit;
        }
        $priKey= openssl_get_privatekey($priKey);
       
        $service_type = "wxpay";
        //$notify_url = "http://www.dinpay.com/Notify_Url.jsp";
        $notify_url = url('/zfnotify'); 
        //echo $notify_url;       
        $interface_version ="V3.0"; 
        $sign_type = "RSA-S";
        //$order_no = "10002016665";
        $order_no = $out_trade_no;
        
        $order_time = date('Y-m-d H:i:s');  
        //$order_amount ="0.01" ;   
        $order_amount = $money;
        $product_name = "充值";   
        $product_code = ""; 
        $product_num = "";
        $product_desc = ""; 
        $extra_return_param = "";   
        $extend_param = "";
        $signStr = "";
        if($extend_param != ""){
            $signStr = $signStr."extend_param=".$extend_param."&";
        }
        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }   
        $signStr = $signStr."interface_version=".$interface_version."&";        
        $signStr = $signStr."merchant_code=".$merchant_code."&";        
        $signStr = $signStr."notify_url=".$notify_url."&";          
        $signStr = $signStr."order_amount=".$order_amount."&";          
        $signStr = $signStr."order_no=".$order_no."&";          
        $signStr = $signStr."order_time=".$order_time."&";  
        if($product_code != ""){
            $signStr = $signStr."product_code=".$product_code."&";
        }       
        if($product_desc != ""){
            $signStr = $signStr."product_desc=".$product_desc."&";
        }
        $signStr = $signStr."product_name=".$product_name."&";

        if($product_num != ""){
            $signStr = $signStr."product_num=".$product_num."&";
        }   
        $signStr = $signStr."service_type=".$service_type;  
        openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
        $sign = urlencode(base64_encode($sign_info));           
        $postdata = "";
        if($extend_param != ""){
            $postdata = $postdata.'extend_param='.$extend_param."&";
        }
        if($extra_return_param != ""){
            $postdata = $postdata.'extra_return_param='.$extra_return_param."&";
        }
        if($product_code != ""){
            $postdata = $postdata.'product_code='.$product_code."&";
        }   
        if($product_desc != ""){
            $postdata = $postdata.'product_desc='.$product_desc."&";
        }   
        if($product_num != ""){
            $postdata = $postdata.'product_num='.$product_num."&";
        }   
        $postdata = $postdata.'merchant_code='.$merchant_code."&";
        $postdata = $postdata.'service_type='.$service_type."&";
        $postdata = $postdata.'notify_url='.$notify_url."&";
        $postdata = $postdata.'interface_version='.$interface_version."&";
        $postdata = $postdata. 'sign_type='.$sign_type."&";
        $postdata = $postdata.'sign='.$sign."&";
        $postdata = $postdata.'order_no='.$order_no."&";
        $postdata = $postdata.'order_time='.$order_time."&";
        $postdata = $postdata.'order_amount='.$order_amount."&";
        $postdata = $postdata.'product_name='.$product_name;
        //echo "发送到智付的数据为："."<br>".$postdata."<br>";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://api.dinpay.com/gateway/api/weixin");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response=curl_exec($ch);
        $res=simplexml_load_string($response);
        //if($data['openid']!='on8j1v9bJGetq2GiZxCSoWW5BJGY'){
            //$this->error('系统更新中');
            //var_dump($res);
        //}
        //var_dump($res);
        $resp_code=$res->response->resp_code;           
        if($resp_code=="SUCCESS"){
            $qrcode=$res->response->trade->qrcode;
            //var_dump($qrcode);
            $pic1="./zfpay/{$out_trade_no}-qrcode.png";
            $pic2="./zfpay/{$out_trade_no}-output.png";
            $errorCorrectionLevel = 'L';
            $matrixPointSize = 10;
            if(file_exists($pic1) or file_exists($pic2)){                               
                unlink($pic1);
                unlink($pic2);
            }
            \QRcode::png ( $qrcode, $pic1, $errorCorrectionLevel, $matrixPointSize, 2 );
            $QR = $pic1;
            $logo = './logo.png';
            if ($logo !== FALSE) {
                $QR = imagecreatefromstring ( file_get_contents ( $QR ) );
                $logo = imagecreatefromstring ( file_get_contents ( $logo ) );
                $QR_width = imagesx ( $QR );
                $QR_height = imagesy ( $QR );
                $logo_width = imagesx ( $logo );
                $logo_height = imagesy ( $logo );
                $logo_qr_width = $QR_width / 7;
                $scale = $logo_width / $logo_qr_width;
                $logo_qr_height = $logo_height / $scale;
                $from_width = ($QR_width - $logo_qr_width) / 2;
                imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );
            }
            imagepng ( $QR, $pic2 );
            imagedestroy($QR);
            //$this->assign('qr',$pic2);
            //$this->display('pay');
            return view('home.payment.saoma',compact('pic2','order_no','money'));
            //echo "扫描二维码支付：" ."<br>"."<img src='{$pic2}'>";
        }
        curl_close($ch);
        
    }


    public function yinLianPay(){
        $money = 0.01;
       
        
        require_once('merchant.php');
       
        $data = array();
       
        
        $data['money'] = $money;
        $data['create_time'] = time();
        $data['is_pay'] = 0;
        $data['pay_type'] = 1;
        $data['bank_id'] = 0;
        //商户单号
        $out_trade_no = date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        // $res = M('FuturesRecharge')->add($data);
        // if(!$res){
        //     $this->error('充值出错！');
        // }
        

        /////////////////////////////////获取商家私钥//////////////////////////////////////
        ////////////////////////get the private key of merchant///////////////////////////
    
    require_once('merchant.php');
    $priKey= openssl_get_privatekey($priKey);
    /////////////////////////////////初始化提交参数//////////////////////////////////////
    ////////////////////////initial the parameter datas/////////////////////////////////
    $merchant_code = "2020600810";
    $service_type ="direct_pay";    
    $interface_version ="V3.0";
    $pay_type = "";
    $sign_type ="RSA-S";
    $input_charset = "UTF-8";
    $notify_url ="http://www.dinpay.com";
    //$notify_url = U('Pay/ylzfnotify');      
    $order_no = $out_trade_no;  
    $order_time = date('Y-m-d H:i:s');  
    $order_amount = $money; 
    $product_name ="账号充值";  
    $product_code = ""; 
    $product_desc = ""; 
    $product_num = "";
    $show_url = ""; 
    $client_ip ="" ;    
    $bank_code = "";    
    $redo_flag = "";    
    $extend_param = "";
    $extra_return_param = "";   
    $return_url ="";        
    
    /////////////////////////////   数据签名  /////////////////////////////////
    ////////////////////////////  Data signature  ////////////////////////////

    /**
    签名规则定义如下：
    （1）参数列表中，除去sign_type、sign两个参数外，其它所有非空的参数都要参与签名，值为空的参数不用参与签名；
    （2）签名顺序按照参数名a到z的顺序排序，若遇到相同首字母，则看第二个字母，以此类推，同时将商家支付密钥key放在最后参与签名，组成规则如下：
            参数名1=参数值1&参数名2=参数值2&……&参数名n=参数值n&key=key值
    */

    /**
    The definition of signature rule is as follows : 
    （1） In the list of parameters, except the two parameters of sign_type and sign, all the other parameters that are not in blank shall be signed, the parameter with value as blank doesn’t need to be signed; 
    （2） The sequence of signature shall be in the sequence of parameter name from a to z, in case of same first letter, then in accordance with the second letter, so on so forth, meanwhile, the merchant payment key shall be put at last for signature, and the composition rule is as follows : 
        Parameter name 1 = parameter value 1& parameter name 2 = parameter value 2& ......& parameter name N = parameter value N & key = key value
    */
    
    $signStr= "";
    
    if($bank_code != ""){
        $signStr = $signStr."bank_code=".$bank_code."&";
    }
    if($client_ip != ""){
        $signStr = $signStr."client_ip=".$client_ip."&";
    }
    if($extend_param != ""){
        $signStr = $signStr."extend_param=".$extend_param."&";
    }
    if($extra_return_param != ""){
        $signStr = $signStr."extra_return_param=".$extra_return_param."&";
    }
    
    $signStr = $signStr."input_charset=".$input_charset."&";    
    $signStr = $signStr."interface_version=".$interface_version."&";    
    $signStr = $signStr."merchant_code=".$merchant_code."&";    
    $signStr = $signStr."notify_url=".$notify_url."&";      
    $signStr = $signStr."order_amount=".$order_amount."&";      
    $signStr = $signStr."order_no=".$order_no."&";      
    $signStr = $signStr."order_time=".$order_time."&";  

    if($pay_type != ""){
        $signStr = $signStr."pay_type=".$pay_type."&";
    }

    if($product_code != ""){
        $signStr = $signStr."product_code=".$product_code."&";
    }   
    if($product_desc != ""){
        $signStr = $signStr."product_desc=".$product_desc."&";
    }
    
    $signStr = $signStr."product_name=".$product_name."&";

    if($product_num != ""){
        $signStr = $signStr."product_num=".$product_num."&";
    }   
    if($redo_flag != ""){
        $signStr = $signStr."redo_flag=".$redo_flag."&";
    }
    if($return_url != ""){
        $signStr = $signStr."return_url=".$return_url."&";
    }   

    if($show_url != ""){
        
        $signStr = $signStr."service_type=".$service_type."&";
        $signStr = $signStr."show_url=".$show_url;
    }else{
        
        $signStr = $signStr."service_type=".$service_type;
    }
    
    openssl_sign($signStr,$sign_info,$priKey,OPENSSL_ALGO_MD5);
    
    $sign = base64_encode($sign_info);
    //$html= "<html>";
    //$html .= "<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>";
    //$html .= "";
echo <<<H
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head> 
    <body onLoad="document.dinpayForm.submit();">
        <form name="dinpayForm" method="post" action="https://pay.dinpay.com/gateway?input_charset=UTF-8" target="_self">
    <input type="hidden" name="sign"          value="{$sign}" />
            <input type="hidden" name="merchant_code" value="{$merchant_code}" />
            <input type="hidden" name="bank_code"     value="{$bank_code}"/>
            <input type="hidden" name="order_no"      value="{$order_no}"/>
            <input type="hidden" name="order_amount"  value="{$order_amount}"/>
            <input type="hidden" name="service_type"  value="{$service_type}"/>
            <input type="hidden" name="input_charset" value="{$input_charset}"/>
            <input type="hidden" name="notify_url"    value="{$notify_url}">
            <input type="hidden" name="interface_version" value="{$interface_version}"/>
            <input type="hidden" name="sign_type"     value="{$sign_type}"/>
            <input type="hidden" name="order_time"    value="{$order_time}"/>
            <input type="hidden" name="product_name"  value="{$product_name}"/>
            <input Type="hidden" Name="client_ip"     value="{$client_ip}"/>
            <input Type="hidden" Name="extend_param"  value="{$extend_param}"/>
            <input Type="hidden" Name="extra_return_param" value="{$extra_return_param}"/>
            <input Type="hidden" Name="pay_type"  value="{$pay_type}"/>
            <input Type="hidden" Name="product_code"  value="{$product_code}"/>
            <input Type="hidden" Name="product_desc"  value="{$product_desc}"/>
            <input Type="hidden" Name="product_num"   value="{$product_num}"/>
            <input Type="hidden" Name="return_url"    value="{$return_url}"/>
            <input Type="hidden" Name="show_url"      value="{$show_url}"/>
            <input Type="hidden" Name="redo_flag"     value="{$redo_flag}"/>
        </form>
    </body>
</html>;
H;
        //echo $html;
    }


    public function zfnotify(Request $request){
        //echo 111;exit;
        //$file = './test.txt';
        
        require_once('merchant.php');
        $pubKey = openssl_get_publickey($pubKey);
        $merchant_code  = $request["merchant_code"];  
        $notify_type = $request["notify_type"];
        $notify_id = $request["notify_id"];
        $interface_version = $request["interface_version"];
        $sign_type = $request["sign_type"];
        $dinpaySign = base64_decode($request["sign"]);
        $order_no = $request["order_no"];
        $order_time = $request["order_time"]; 
        $order_amount = $request["order_amount"];
        $extra_return_param = $request["extra_return_param"];
        $trade_no = $request["trade_no"];
        $trade_time = $request["trade_time"];
        $trade_status = $request["trade_status"];
        $bank_seq_no = $request["bank_seq_no"];
        $signStr = "";
        if($bank_seq_no != ""){
            $signStr = $signStr."bank_seq_no=".$bank_seq_no."&";
        }

        if($extra_return_param != ""){
            $signStr = $signStr."extra_return_param=".$extra_return_param."&";
        }   
        $signStr = $signStr."interface_version=".$interface_version."&";    
        $signStr = $signStr."merchant_code=".$merchant_code."&";
        $signStr = $signStr."notify_id=".$notify_id."&";
        $signStr = $signStr."notify_type=".$notify_type."&";
        $signStr = $signStr."order_amount=".$order_amount."&";  
        $signStr = $signStr."order_no=".$order_no."&";  
        $signStr = $signStr."order_time=".$order_time."&";  
        $signStr = $signStr."trade_no=".$trade_no."&";  
        $signStr = $signStr."trade_status=".$trade_status."&";  
        $signStr = $signStr."trade_time=".$trade_time;       
        if(openssl_verify($signStr,$dinpaySign,$pubKey,OPENSSL_ALGO_MD5)){          
            
            $out_trade_no = $order_no;
            
            $recharge = DB::table('recharges')
                ->where('out_trade_no', '=', $out_trade_no)
                ->where('status','=',0)->first();

            if(!$recharge){
                return;
            }    

            $set = array();
            $set['transaction_id'] = $notify_id;
            $set['status'] = 1;
            $set['pay_time'] = $trade_time;
            $where = array();
           
            $res = DB::table('recharges')->where('id','=',$recharge->id)->update($set);
            if(!$res){
                return false;
            }
            $money = $order_amount/100;
            $user = $this->user->find($recharge->user_id);
            if($user){
                //file_put_contents($file,$user->mobile.'-1345');
                $this->user->modifyBalance($user->id,$recharge->money,1,'账户充值');
            }
            //modify_account($openid,$order_amount,1,'充值');
            
            echo "SUCCESS"; 
            
            exit;
            
        }else{
            echo "Signature verification failed";  
           
        }
    }

    public function businessCard(Request $request){
        $user = Auth::user();
        return view('home.user.businesscard',compact('user'));
    }

     

    //----------------------------------上传裁剪图片-------------------------------------
    private $src;
    private $data;
    private $file;
    private $dst;
    private $type;
    private $extension;
    private $msg;

    public function uploadBusinessCard(Request $request){

        $src = $_POST['avatar_src'];
        $data = $_POST['avatar_data'];
        $file = $_FILES['avatar_file'];
        $this -> setSrc($src);
        $this -> setData($data);
        $this -> setFile($file);
        $this -> crop($this -> src, $this -> dst, $this -> data);
        $response = array(
            'state'  => 200,
            'message' => $this -> getMsg(),
            'result' => $this -> getResult()
          );
        echo json_encode($response);
        return;
    }

    // function __construct($src, $data, $file) {
    //   $this -> setSrc($src);
    //   $this -> setData($data);
    //   $this -> setFile($file);
    //   $this -> crop($this -> src, $this -> dst, $this -> data);
    // }

    private function setSrc($src) {
      if (!empty($src)) {
        $type = exif_imagetype($src);

        if ($type) {
          $this -> src = $src;
          $this -> type = $type;
          $this -> extension = image_type_to_extension($type);
          $this -> setDst();
        }
      }
    }

    private function setData($data) {
      if (!empty($data)) {
        $this -> data = json_decode(stripslashes($data));
      }
    }

    private function setFile($file) {
      $errorCode = $file['error'];

      if ($errorCode === UPLOAD_ERR_OK) {
        $type = exif_imagetype($file['tmp_name']);

        if ($type) {
          $extension = image_type_to_extension($type);
          //$src = 'upload/' . date('YmdHis') . '.original' . $extension;
          $src = 'upload/home/user/businesscard/' . date('YmdHis') . '.original' . $extension;
          
          if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {

            if (file_exists($src)) {
              unlink($src);
            }

            $result = move_uploaded_file($file['tmp_name'], $src);

            if ($result) {
              $this -> src = $src;
              $this -> type = $type;
              $this -> extension = $extension;
              $this -> setDst();
            } else {
               $this -> msg = 'Failed to save file';
            }
          } else {
            $this -> msg = 'Please upload image with the following types: JPG, PNG, GIF';
          }
        } else {
          $this -> msg = 'Please upload image file';
        }
      } else {
        $this -> msg = $this -> codeToMessage($errorCode);
      }
    }

    private function setDst() {
      //$this -> dst = 'upload/' . date('YmdHis') . '.png';
      $this -> dst = 'upload/home/user/businesscard/' . date('YmdHis') . '.png';
    }

    private function crop($src, $dst, $data) {
      if (!empty($src) && !empty($dst) && !empty($data)) {
        switch ($this -> type) {
          case IMAGETYPE_GIF:
            $src_img = imagecreatefromgif($src);
            break;

          case IMAGETYPE_JPEG:
            $src_img = imagecreatefromjpeg($src);
            break;

          case IMAGETYPE_PNG:
            $src_img = imagecreatefrompng($src);
            break;
        }

        if (!$src_img) {
          $this -> msg = "Failed to read the image file";
          return;
        }

        $size = getimagesize($src);
        $size_w = $size[0]; // natural width
        $size_h = $size[1]; // natural height

        $src_img_w = $size_w;
        $src_img_h = $size_h;

        $degrees = $data -> rotate;

        // Rotate the source image
        if (is_numeric($degrees) && $degrees != 0) {
          // PHP's degrees is opposite to CSS's degrees
          $new_img = imagerotate( $src_img, -$degrees, imagecolorallocatealpha($src_img, 0, 0, 0, 127) );

          imagedestroy($src_img);
          $src_img = $new_img;

          $deg = abs($degrees) % 180;
          $arc = ($deg > 90 ? (180 - $deg) : $deg) * M_PI / 180;

          $src_img_w = $size_w * cos($arc) + $size_h * sin($arc);
          $src_img_h = $size_w * sin($arc) + $size_h * cos($arc);

          // Fix rotated image miss 1px issue when degrees < 0
          $src_img_w -= 1;
          $src_img_h -= 1;
        }

        $tmp_img_w = $data -> width;
        $tmp_img_h = $data -> height;
        $dst_img_w = 220;
        $dst_img_h = 220;

        $src_x = $data -> x;
        $src_y = $data -> y;

        if ($src_x <= -$tmp_img_w || $src_x > $src_img_w) {
          $src_x = $src_w = $dst_x = $dst_w = 0;
        } else if ($src_x <= 0) {
          $dst_x = -$src_x;
          $src_x = 0;
          $src_w = $dst_w = min($src_img_w, $tmp_img_w + $src_x);
        } else if ($src_x <= $src_img_w) {
          $dst_x = 0;
          $src_w = $dst_w = min($tmp_img_w, $src_img_w - $src_x);
        }

        if ($src_w <= 0 || $src_y <= -$tmp_img_h || $src_y > $src_img_h) {
          $src_y = $src_h = $dst_y = $dst_h = 0;
        } else if ($src_y <= 0) {
          $dst_y = -$src_y;
          $src_y = 0;
          $src_h = $dst_h = min($src_img_h, $tmp_img_h + $src_y);
        } else if ($src_y <= $src_img_h) {
          $dst_y = 0;
          $src_h = $dst_h = min($tmp_img_h, $src_img_h - $src_y);
        }

        // Scale to destination position and size
        $ratio = $tmp_img_w / $dst_img_w;
        $dst_x /= $ratio;
        $dst_y /= $ratio;
        $dst_w /= $ratio;
        $dst_h /= $ratio;

        $dst_img = imagecreatetruecolor($dst_img_w, $dst_img_h);

        // Add transparent background to destination image
        imagefill($dst_img, 0, 0, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
        imagesavealpha($dst_img, true);

        $result = imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);

        if ($result) {
          if (!imagepng($dst_img, $dst)) {
            $this -> msg = "Failed to save the cropped image file";
          }else{
            //保存进用信息
            $user = Auth::user();
            $user->business_card = $dst;
            $user->save();
          }
        } else {
          $this -> msg = "Failed to crop the image file";
        }

        imagedestroy($src_img);
        imagedestroy($dst_img);
      }
    }

    private function codeToMessage($code) {
      switch ($code) {
        case UPLOAD_ERR_INI_SIZE:
          $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
          break;

        case UPLOAD_ERR_FORM_SIZE:
          $message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
          break;

        case UPLOAD_ERR_PARTIAL:
          $message = 'The uploaded file was only partially uploaded';
          break;

        case UPLOAD_ERR_NO_FILE:
          $message = 'No file was uploaded';
          break;

        case UPLOAD_ERR_NO_TMP_DIR:
          $message = 'Missing a temporary folder';
          break;

        case UPLOAD_ERR_CANT_WRITE:
          $message = 'Failed to write file to disk';
          break;

        case UPLOAD_ERR_EXTENSION:
          $message = 'File upload stopped by extension';
          break;

        default:
          $message = 'Unknown upload error';
      }

      return $message;
    }

    public function getResult() {
      return !empty($this -> data) ? $this -> dst : $this -> src;
    }

    public function getMsg() {
      return $this -> msg;
    }
    //----------------------------------上传裁剪图片结束-------------------------------------

    //----------------------------------中兴支付开始---------------------------------------------
    public function gzzh(Request $request){
        
        $this->validate($request, [
            'money' => 'required|numeric|min:10'
        ]);

        $user = $request->user();
        $data = array();
        $money = $request->money;
        $data['user_id'] = $user->id;
        $data['money'] = $money;
        $data['fee'] = $money*0.009;
        $data['status'] = 0;
        $data['type'] = 2;
        $data['created_at'] = \Carbon\Carbon::now()->toDateTimeString();

        //商户单号
        $out_trade_no = $user->id.date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        $id = DB::table('recharges')->insertGetId($data);
        if(!$id){
            echo 'Error';exit;
        }
        
        
        $zhdata['method']='submitOrderInfo';

        $zhdata['out_trade_no']=$out_trade_no;
        $zhdata['sub_openid']=$user->openid;
        $zhdata['body']='账户充值';
        $zhdata['total_fee']= $money*100 ;
        //$zhdata['mch_create_ip']='127.0.0.1';
        $zhdata['mch_create_ip']=$this->getIPaddress();
        //var_dump($zhdata);
        include(base_path().'/libs/Gzzh/Request.class.php');
        //$order = \Request::submitOrderInfo($zhdata);

        $request = new \Request();
        //var_dump($request);
        $token_id = $request->submitOrderInfo($zhdata);
        //var_dump($token_id);die;
        $url = "https://pay.swiftpass.cn/pay/jspay?token_id=".$token_id."&showwxtitle=1";
        //$url = "https://pay.swiftpass.cn/pay/jspay?token_id=".$token_id;
        //die;
        header("Location:".$url);
        //var_dump($url);
    }
    
    function getIPaddress(){

        $IPaddress='';
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $IPaddress = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $IPaddress = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $IPaddress = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $IPaddress = getenv("HTTP_CLIENT_IP");
            } else {
                $IPaddress = getenv("REMOTE_ADDR");
            }
        }
        return $IPaddress;
    }
    
    public function gzzhnotify(){
        include(base_path().'/libs/Gzzh/Request.class.php');
        $request = new \Request();
        $request->callback();
        
        //$_POST['test'] = 'Jy';
        //file_put_contents('./zhdata.txt',json_encode($_POST));
        
    }
    //----------------------------------中兴支付结束---------------------------------------------

    //兴业扫码支付---start
    public function xysmPay(Request $request){
        include(base_path().'/libs/WxPayPubHelper/WxPayPubHelper.class.php');
        //import('Futures.WxPayPubHelper.WxPayPubHelper');
        $this->validate($request, [
            'money' => 'required|numeric|min:10|max:20000'
        ]);

        $user = $request->user();
        $data = array();
        $money = $request->money;
        $data['user_id'] = $user->id;
        $data['money'] = $money;
        $data['fee'] = $money*0.009;
        $data['status'] = 0;
        $data['type'] = 2;
        $data['created_at'] = \Carbon\Carbon::now()->toDateTimeString();

        //商户单号
        $out_trade_no = 'zdgj'.$data['user_id'].date("YmdHis").mt_rand(1000,9999);
        $data['out_trade_no'] = $out_trade_no;
        $id = DB::table('recharges')->insertGetId($data);
        if(!$id){
            echo 'Error';exit;
        }
        
        //兴业支付
        $total_fee = $money*100;
        $order_no = $out_trade_no;
        //$this->assign('order_no',$out_trade_no);
        //$this->assign('money',$money);
        try{
            $unifiedOrder = new \UnifiedOrder_pub();
            
            $unifiedOrder->setParameter("body", "APP支付");//商品描述
            $timeStamp = time();
            //$out_trade_no = "app".$timeStamp;
            $unifiedOrder->setParameter("out_trade_no", "$out_trade_no");//商户订单号 
            $unifiedOrder->setParameter("total_fee", $total_fee);//总金额
            $unifiedOrder->setParameter("trade_type", "NATIVE");//交易类型
            $notify_url = url('xysmnotify');
            //$unifiedOrder->setParameter("notify_url", "http://qtest.fivip.com/apppay/id.php");
            $unifiedOrder->setParameter("notify_url", $notify_url);


            $appParameters = $unifiedOrder->getAppParameters();
            //var_dump($appParameters);die;
            //echo $appParameters['code_url'];
            
            if($appParameters['return_code']=="SUCCESS"){
                include ('phpqrcode.php');
                $qrcode=$appParameters['code_url'];
                //var_dump($qrcode);
                $pic1="./zfpay/{$out_trade_no}-qrcode.png";
                $pic2="./zfpay/{$out_trade_no}-output.png";
                $errorCorrectionLevel = 'L';
                $matrixPointSize = 10;
                if(file_exists($pic1) or file_exists($pic2)){                               
                    unlink($pic1);
                    unlink($pic2);
                }
                \QRcode::png ( $qrcode, $pic1, $errorCorrectionLevel, $matrixPointSize, 2 );
                $QR = $pic1;
                $logo = './logo.png';
                if ($logo !== FALSE) {
                    $QR = imagecreatefromstring ( file_get_contents ( $QR ) );
                    $logo = imagecreatefromstring ( file_get_contents ( $logo ) );
                    $QR_width = imagesx ( $QR );
                    $QR_height = imagesy ( $QR );
                    $logo_width = imagesx ( $logo );
                    $logo_height = imagesy ( $logo );
                    $logo_qr_width = $QR_width / 7;
                    $scale = $logo_width / $logo_qr_width;
                    $logo_qr_height = $logo_height / $scale;
                    $from_width = ($QR_width - $logo_qr_width) / 2;
                    imagecopyresampled ( $QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height );
                }
                imagepng ( $QR, $pic2 );
                imagedestroy($QR);
                //echo $pic2;
                //$this->assign('qr',$pic2);
                //$this->display('pay');
                //echo "扫描二维码支付：" ."<br>"."<img src='{$pic2}'>";
                return view('home.payment.saoma',compact('pic2','order_no','money'));
            }
            

        }catch(Exception $wxexception)
        {
        }
        //-------
        

    }

    public function xysmNotify(){
        //import('Futures.ZfPay.wechatPay');
        include(base_path().'/libs/WxPayPubHelper/WxPayPubHelper.class.php');
        try{
            $unifiedOrder = new \UnifiedOrder_pub();
            $appParameters = $unifiedOrder->getParameters($this->user);
            //逻辑、数据处理
            //file_put_contents('a.txt',$appParameters,FILE_APPEND);
            //echo $appParameters['total_fee'];
            $appParameters=json_decode($appParameters,true);//json转数组

        }catch(Exception $wxexception)
        {
            exit;
        }
        //成功返回参数
        $arry['version']=$appParameters['version'];
        $arry['return_code']='SUCCESS';
        echo  $unifiedOrder->arrayToXml($arry);
        
    }
    //兴业扫码支付---end

}